package com.project.personal_blog.garbage_classification_management_system.service.Impl;

import com.project.personal_blog.garbage_classification_management_system.mapper.loginMapper;
import com.project.personal_blog.garbage_classification_management_system.pojo.Code;
import com.project.personal_blog.garbage_classification_management_system.pojo.Result;
import com.project.personal_blog.garbage_classification_management_system.pojo.User;
import com.project.personal_blog.garbage_classification_management_system.service.LoginService;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private loginMapper loginMapper;
    private PasswordEncoder passwordEncoder;

    @Override
    public Result login(String username, @NotNull String password) {
        if (password.length() < 8 || password.length() > 16) {
            return new Result("fail", Code.PASSWORD_LENGTH_ERROR, "密码长度必须在8到16位之间");
        }
        if (!password.matches("^(?=.*[0-9])(?=.*[a-zA-Z])(?=.*[!@#$%^&*]).{8,16}$")) {
            return new Result("fail", Code.PASSWORD_FORMAT_ERROR, "密码必须包含字母、数字和符号");
        }
        // 验证用户名和密码
        User loginUser = loginMapper.login(username, passwordEncoder.encode(password));
        if (loginUser != null) {
            return new Result("success", Code.LOGIN_SUCCESS, loginUser);
        } else {
            return new Result("fail", Code.LOGIN_FAIL, "用户名或密码错误");
        }
    }
}
